<template>
  <div id="userLayout" class="user-layout-wrapper">
    <div class="container">
      <el-container>
        <div class="login-top-bg"></div>
      </el-container>
    </div>
    <div class="logo">
      <!-- <img src="../../../src/assets/slices/top2.png" height="110px" /> -->
    </div>
    <div class="login-main">
      <div class="login-title">
        <span>欢迎登录</span>
      </div>
      <el-card>
        <div class="login-content">
          <div class="login-form-div">
            <div class="login-tab">
              <span
                :class="loginType == 1 ? 'active' : ''"
                @click="changeType(1)"
                >账号密码登录</span
              ><span
                :class="loginType == 2 ? 'active' : ''"
                @click="changeType(2)"
                >短信验证码登录</span
              >
            </div>
            <el-form
              class="login-form"
              :model="pwdForm"
              :rules="pwdFormRules"
              ref="loginForm"
              v-if="loginType == 1"
            >
              <el-form-item prop="username">
                <el-input
                  placeholder="请输入账号"
                  maxlength="20"
                  v-model="pwdForm.username"
                  prefix-icon="el-icon-user"
                  clearable
                  @keyup.enter.native="
                    loginEvent(pwdForm.username, pwdForm.password)
                  "
                />
              </el-form-item>
              <el-form-item style="position: relative" prop="password">
                <el-input
                  class="enter-code enter-password"
                  v-model="pwdForm.password"
                  name="logVerify"
                  placeholder="请输入密码"
                  prefix-icon="el-icon-key"
                  clearable
                  type="password"
                  @keyup.enter.native="
                    loginEvent(pwdForm.username, pwdForm.password)
                  "
                />
              </el-form-item>
              <!-- <el-form-item style="position: relative">
                <el-input
                  class="enter-code"
                  v-model="loginForm.captcha"
                  name="logVerify"
                  placeholder="请输入图形验证码"
                  maxlength="6"
                  style="width: 60%"
                  prefix-icon="el-icon-key"
                  clearable
                />
                <div class="vPic">
                  <img
                    v-if="picPath"
                    :src="picPath"
                    width="100%"
                    height="100%"
                    alt="请输入验证码"
                    @click="loginVefify()"
                  />
                </div>
              </el-form-item> -->
              <el-form-item>
                <el-button
                  class="login-submit"
                  type="primary"
                  :loading="loginLoading"
                  v-preventReClick="3000"
                  @click="loginEvent(pwdForm.username, pwdForm.password)"
                  @keyup.enter.native="
                    loginEvent(pwdForm.username, pwdForm.password)
                  "
                  >登 录</el-button
                >
              </el-form-item>
            </el-form>
            <el-form
              class="login-form"
              :model="loginForm"
              :rules="rules"
              ref="loginForm"
              v-if="loginType == 2"
            >
              <el-form-item prop="mobile">
                <el-input
                  placeholder="请输入手机号码"
                  maxlength="11"
                  v-model="loginForm.mobile"
                  prefix-icon="el-icon-user"
                  clearable
                  @keyup.enter.native="
                    loginEvent(loginForm.code, loginForm.mobile)
                  "
                />
              </el-form-item>
              <el-form-item style="position: relative">
                <el-input
                  class="enter-code border-right__none"
                  v-model="loginForm.code"
                  name="logVerify"
                  placeholder="请输入短信验证码"
                  prefix-icon="el-icon-key"
                  clearable
                />
                <div class="phone-code">
                  <el-button
                    slot="append"
                    type="primary"
                    v-preventReClick="2000"
                    :loading="loading"
                    @click="sendPhoneCode(loginForm.mobile)"
                    >{{ !loading ? "发送验证码" : `${cd}s 后再试` }}</el-button
                  >
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  class="login-submit"
                  type="primary"
                  :loading="loginLoading"
                  @click="loginByPhoneEvent(loginForm.code, loginForm.mobile)"
                  v-preventReClick="3000"
                  @keyup.enter.native="
                    loginByPhoneEvent(loginForm.code, loginForm.mobile)
                  "
                  >登 录</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </div>
    <form-dialog ref="formDialog" class="roleForm">
      <template #slot-type="{ scope }">
        <el-radio-group v-model="scope.type">
          <el-radio
            :label="index"
            v-for="(item, index) in roleList"
            :key="index"
          >
            <div class="selectRolesItem">
              <span :title="item.orgName">{{ item.orgName }}</span>
              <span class="b" :title="item.workUnit">{{ item.workUnit }}</span>
            </div>
          </el-radio>
        </el-radio-group>
      </template>
    </form-dialog>
  </div>
</template>

<script>
import dbl from "@/utils/dbl";
import Base64 from "base-64";
import { mapActions } from "vuex";
import { captcha, getPhoneCode } from "@/api/user";
// 引入表单验证插件
import form from "@/utils/formValidation";
import store from "@/store/index.js";
import { getUserRouter, resetRouter } from "@/router/index.js";
export default {
  name: "Login",
  data() {
    const checkPhoneNumber = (rule, value, callback) => {
      if (form._isNullOrEmpty(value)) {
        return callback(new Error("请输入手机号"));
      } else if (value.length !== 11) {
        return callback(new Error("手机号长度需为11位"));
      } else if (!form._isMobile(value)) {
        return callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      loginLoading: false,
      loading: false,
      cd: 60,
      pwdForm: {
        username: "",
        password: "",
      },
      loginForm: {
        mobile: "",
        code: "",
      },
      pwdFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      rules: {
        mobile: [{ validator: checkPhoneNumber, trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      logVerify: "",
      picPath: "",
      loginType: 1,
      roleList: [],
    };
  },
  watch: {
    $route: {
      handler(val) {
        // 逻辑操作
       let code =  window.location?.search
       if(code) {
        let data = {
          body: {
            code: code?.split("?code=")[1]
          },
        };
        this.$api.AdminController.idaas_callbak(data, null, this.$error).then(async (res)=>{
          await store.commit(
              "user/setRolesList",
              res.data?.length ? res.data : []
            );
            // 弹窗选角色
            if (res.data && res.data.length == 1) {
              this.changeRole(res.data[0]);
            }
            if (res.data && res.data.length >= 2) {
              this.roleList = res.data;
              this.loginLoading = false;
              this.$refs.formDialog.open({
                width: "760px",
                title: "请选择管理员单位节点",
                on: {
                  open: (
                    form,
                    { showLoading, hideLoading, $refs, close, rebind }
                  ) => {
                    // 表单打开时open事件处理
                  },
                  submit: async (form, { close, done, $refs }) => {
                    // 点击确定按钮时且表单校验通过的submit事件处理
                    this.changeRole(res?.data[form.type]);
                  },
                },
                // 需要渲染的表单项
                items: [
                  {
                    prop: "type",
                    value: 0,
                    rules: {
                      required: true,
                      message: "请选择您的角色",
                      trigger: "blur",
                    },
                    component: "slot-type",
                  },
                ],
              });
            }
        })
       }
      },
      immediate:true,//第一次就执行
    },
  },
  created() {
    // this.loginVefify();
    console.log("当前时间：", new Date().getTime());
    let nowDate = new Date(new Date().getTime() + 1000 * 60);
    console.log("nowDate:", nowDate);
  },
  methods: {
    ...mapActions("user", ["LoginIn"]),
    // 调用登录接口
    loginEvent(username, password) {
      this.$refs["loginForm"].validate(async (valid) => {
        // 手机号码校验通过
        if (!valid) return false;
        // 已输入验证码
        // if (!this.loginForm.captcha || !this.loginForm.code) {
        //   this.$message({ type: "error", message: "请输入验证码" });
        //   return false;
        // }
        this.loginLoading = true;
        // store.commit("user/setUserInfo", res.body)
        let data = {
          body: {
            username,
            password,
          },
        };
        this.$api.AdminController.pwd(data, null, this.$error).then(
          async (res) => {
            console.log(res);

            await store.commit(
              "user/setRolesList",
              res.data?.length ? res.data : []
            );
            // 弹窗选角色
            if (res.data && res.data.length == 1) {
              this.changeRole(res.data[0]);
            }
            if (res.data && res.data.length >= 2) {
              this.roleList = res.data;
              this.loginLoading = false;
              this.$refs.formDialog.open({
                width: "760px",
                title: "请选择管理员单位节点",
                on: {
                  open: (
                    form,
                    { showLoading, hideLoading, $refs, close, rebind }
                  ) => {
                    // 表单打开时open事件处理
                  },
                  submit: async (form, { close, done, $refs }) => {
                    // 点击确定按钮时且表单校验通过的submit事件处理
                    this.changeRole(res?.data[form.type]);
                  },
                },
                // 需要渲染的表单项
                items: [
                  {
                    prop: "type",
                    value: 0,
                    rules: {
                      required: true,
                      message: "请选择您的角色",
                      trigger: "blur",
                    },
                    component: "slot-type",
                  },
                  // {
                  //   label: "名称",
                  //   prop: "name",
                  //   value: "",
                  //   span: 12,
                  //   rules: {
                  //     required: true,
                  //     trigger: "blur",
                  //     message: "请输入角色名称",
                  //   },
                  //   component: {
                  //     name: "el-input",
                  //     attrs: {
                  //       placeholder: "请输入角色名称",
                  //     },
                  //   },
                  // },
                ],
              });
            }
          }
        );
      });
    },
    async changeRole(data) {
      let body = data;
      // body.menuPermission=""
      let userRouters = getUserRouter(body ? body.menuPermission : "", body);
      await store.commit("SET_ROUTERS", userRouters);
      await store.commit("user/setUserInfo", body);
      await store.commit("user/setToken", Base64.encode(body.phone));
      resetRouter();
      await store.commit("user/setCurrentUserInfo", "");
      await store.commit("user/setLocalPageSteps", "");
      // dbl.set("localPageSteps", "");
      let menu = userRouters[0].children[0];
      console.log("menu", menu);
      // this.$router.push('/jydw-list?menuId=1000000010')
      this.link(menu.name, menu.meta.query);
      this.loginLoading = false;
    },
    // 调用登录接口
    loginByPhoneEvent(code, mobile) {
      this.$refs["loginForm"].validate(async (valid) => {
        // 手机号码校验通过
        if (!valid) return false;
        this.loginLoading = true;
        let data = {
          body: {
            mobile,
            code,
          },
        };

        this.$api.AdminController.login(data, null, this.$error).then(
          async (res) => {
            await store.commit(
              "user/setRolesList",
              res.data?.length ? res.data : []
            );
            // 弹窗选角色
            if (res.data && res.data.length == 1) {
              this.changeRole(res.data[0]);
            }
            if (res.data && res.data.length >= 2) {
              this.roleList = res.data;
              this.loginLoading = false;
              this.$refs.formDialog.open({
                width: "760px",
                title: "请选择管理员单位节点",
                on: {
                  open: (
                    form,
                    { showLoading, hideLoading, $refs, close, rebind }
                  ) => {
                    // 表单打开时open事件处理
                  },
                  submit: async (form, { close, done, $refs }) => {
                    // 点击确定按钮时且表单校验通过的submit事件处理
                    this.changeRole(res?.data[form.type]);
                  },
                },
                // 需要渲染的表单项
                items: [
                  {
                    prop: "type",
                    value: 0,
                    rules: {
                      required: true,
                      message: "请选择您的角色",
                      trigger: "blur",
                    },
                    component: "slot-type",
                  },
                ],
              });
            }
          }
        );
      });
    },

    // 调用图形验证码接口
    // async loginVefify() {
    //   await captcha({}).then((ele) => {
    //     this.loginForm.captcha = "";
    //     this.picPath = ele.data.image;
    //     this.loginForm.captchaID = ele.data.captchaID;
    //   });
    // },

    // 调用短信验证码接口
    async sendPhoneCode(mobile) {
      this.$refs["loginForm"].validate(async (valid) => {
        // 手机号码校验是否合法
        if (!valid) {
          return false;
        }

        // 图形验证码校验是否合法
        // if (this.loginForm.captcha.length !== 6) {
        //   this.$message({ type: "error", message: "请输入正确的图形验证码" });
        //   return false;
        // }
        let data = {
          body: {
            mobile,
          },
        };
        this.$api.AdminController.smsotp(data, null, this.$error)
          .then((res) => {
            if (res.code === 0) {
              this.$message({ type: "success", message: "已发送短信验证码" });
              // 事件完成后将按钮加载状态流转为false并设置CD为60s
              // 需将此处CD存储在本地，防止用户刷新页面后CD重置为0
              let timer = setInterval(() => {
                if (this.cd) {
                  this.cd = this.cd - 1;
                  this.loading = true;
                } else {
                  this.loading = false;
                  this.cd = 60;
                  clearInterval(timer);
                }
              }, 1000);
            }
          })
          .catch((err) => {
            // this.loginVefify();
            console.log("err:", err);
          });
      });
    },
    changeType(type) {
      this.loginType = type;
    },
  },
};
</script>

<style lang="scss">
@import "./login.scss";
.roleForm {
  .el-form-item__content {
    margin-left: 0px !important;
    .el-radio-group {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .el-radio {
        display: block;
        margin: 0px 7px !important;
        font-size: 16px;
        .el-radio__input {
          white-space: nowrap;
          opacity: 0;
          cursor: pointer;
          line-height: 1;
          position: absolute;
          right: 0px;
          top: 30px;
        }
      }
    }
  }
  .el-radio__label {
    color: #fff;
    font-size: 16px;
  }
  .el-dialog__body {
    padding: 0px 20px;
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .selectRolesItem {
    width: 342px;
    height: 92px;
    background: url(../../assets/login/bg-normal.png) no-repeat;
    background-size: 100% 100%;
    box-sizing: border-box;
    padding: 25px 30px 30px 100px;
    span {
      display: block;
      padding: 3px 0;
      color: #fff;
      max-width: 212px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      &.b {
        font-weight: 700;
      }
    }
  }
  .is-checked {
    .selectRolesItem {
      width: 342px;
      height: 92px;
      background: url(../../assets/login/bg-click.png) no-repeat;
      background-size: 100% 100%;
      box-sizing: border-box;
      padding: 30px 30px 30px 100px;
      span {
        display: block;
        padding: 3px 0;
        color: #4af6fc;
      }
    }
  }
}
</style>
